package com.lhy.gulimall.product.exception;

import com.lhy.common.exception.BizCodeEnum;
import com.lhy.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 统一处理异常
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.lhy.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    private R handleValidException(MethodArgumentNotValidException exception) {
        log.error("数据校验出现问题{},异常类型{}", exception.getMessage(), exception.getCause());
        BindingResult bindingResult = exception.getBindingResult();
        Map<String, String> map = new HashMap<>();
        // 获取校验的错误结果
        bindingResult.getFieldErrors().forEach(item->{
            //filedError 获取到字段提示信息
            String message = item.getDefaultMessage();
            // 获取到属性名
            String field = item.getField();
            map.put(field, message);
        });
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(), BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data", map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable t){
        t.printStackTrace();
        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(), BizCodeEnum.UNKNOW_EXCEPTION.getMsg());

    }
}
